package com.szbmyoubao.app.ui.login

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.timer.tickFlow
import com.szbmyoubao.app.ui.MainActivity
import com.szbmyoubao.app.ui.login.forget.ForgetPwdActivity
import com.szbmyoubao.app.ui.login.register.RegisterActivity
import com.szbmyoubao.app.ui.webview.WebHelper
import com.szbmyoubao.app.view.dialog.VersionUpdateDialog
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityLoginBinding
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/13 16:09
 * @des
 */
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding, LoginViewModel>(),
    View.OnClickListener {
    // (属性) 用于取消，确保不会重复收集流
    private var mTickJob: Job? = null
    private var isPwd = false
    override val userBaseTitle: Boolean
        get() = false

    companion object {
        fun launch(context: Context) {
            context.startActivity(Intent(context, LoginActivity::class.java))
        }
    }

    override fun inflateBinding(): ActivityLoginBinding =
        ActivityLoginBinding.inflate(layoutInflater)

    override fun initialize(savedInstanceState: Bundle?) {
        selectLoginPassword()
        checkHasNewVersion()
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is LoginState.SmdCodeSuccess -> {
                    ToastUtils.show("验证码已发送")
                    countDown()
                }

                is LoginState.LoginSuccess -> {
                    ToastUtils.show("登录成功")
                    MainActivity.Companion.launch(this)
                    finish()

                }

                is LoginState.ShowDialog -> {
                    VersionUpdateDialog(this, it.data).show()
                }

                else -> {}
            }
        }
    }


    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            titleBar(binding.toolBar)
        }
    }

    override val darkFont: Boolean
        get() = false
    private val textWatch = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            val phone = binding.etPhone.text.toString().trim()
            if (isPwd) {
                val password = binding.etPassword.text.toString().trim()
                binding.tvLogin.isEnabled = phone.isNotEmpty() && phone.length >= 11 && password.isNotEmpty()
            } else {
                val code = binding.etSmsCode.text.toString().trim()
                binding.tvLogin.isEnabled = phone.isNotEmpty() && phone.length >= 11 && code.isNotEmpty()
            }
        }

    }

    override fun initEvent() {
        binding.ivEye.setOnClickListener(this)
        binding.tvUserAgreement.setOnClickListener(this)
        binding.tvPrivateAgreement.setOnClickListener(this)
        binding.tvPasswordLogin.setOnClickListener(this)
        binding.tvSmsLogin.setOnClickListener(this)
        binding.tvLogin.setOnClickListener(this)
        binding.tvRegister.setOnClickListener(this)
        binding.tvSendTitle.setOnClickListener(this)
        binding.btnForgetPwd.setOnClickListener(this)
        binding.etPhone.addTextChangedListener(textWatch)
        binding.etPassword.addTextChangedListener(textWatch)
        binding.etSmsCode.addTextChangedListener(textWatch)
    }


    override fun initData() {
    }


    private fun showPasswordLayout() {
        binding.viewPassword.visibility = View.VISIBLE
        binding.viewSms.visibility = View.GONE
        selectLoginPassword()
    }

    private fun showSmsLayout() {
        binding.viewPassword.visibility = View.GONE
        binding.viewSms.visibility = View.VISIBLE
        selectLoginPassword()
    }


    private fun selectLoginPassword() {
        binding.ivPwdSelect.visibility = if (isPwd) View.VISIBLE else View.GONE
        binding.ivSmsSelect.visibility = if (isPwd) View.GONE else View.VISIBLE
    }

    /**
     * 密码是否可见
     * 1 明文
     */
    private fun setEysSee(editText: EditText, imageView: ImageView) {
        if (editText.inputType == 1) {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        } else {
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
        }
        setSye(imageView, editText.inputType == 1)
        //光标位置
        editText.setSelection(editText.text.toString().length)
    }

    private fun setSye(imageView: ImageView, isSee: Boolean) {
        imageView.setImageResource(if (isSee) R.mipmap.icon_eye_open else R.mipmap.icon_eye_close)
    }

    override fun onClick(view: View) {
        when (view.id) {

            R.id.tv_password_login -> {
                isPwd = true
                viewModel.changeLogin(0)
                showPasswordLayout()

            }

            R.id.tv_sms_login -> {
                isPwd = false
                viewModel.changeLogin(1)
                showSmsLayout()
            }

            R.id.tv_send_title -> {
                val phone = binding.etPhone.text.toString().trim()
                if (phone.isEmpty() || phone.length < 11) {
                    ToastUtils.show("请输入正确的手机号")
                    return
                }
                VerificationCodeActivity.launch(this, 1002)
            }

            R.id.tv_login -> {
                if (!binding.ivCheck.checked) {
                    ToastUtils.show("请阅读并同意用户协议和隐私政策")
                    return
                }
                val phone = binding.etPhone.text.toString().trim()
                val password = binding.etPassword.text.toString().trim()
                val code = binding.etSmsCode.text.toString().trim()

                lifecycleScope.launch {
                    viewModel.intentChannel.send(
                        LoginIntent.Login(
                            phone = phone,
                            password = password,
                            code = code
                        )
                    )
                }
            }

            R.id.tv_register -> {
                RegisterActivity.Companion.launch(this)
            }

            R.id.iv_eye -> {
                setEysSee(binding.etPassword, binding.ivEye)
            }

            R.id.btn_forget_pwd -> {
                ForgetPwdActivity.Companion.launch(this, 0)
            }

            binding.tvUserAgreement.id -> {
                WebHelper.Companion.toUserAgreement(this)
            }

            binding.tvPrivateAgreement.id -> {
                WebHelper.Companion.toPrivateAgreement(this)
            }
        }
    }

    // (函数)，开始倒计时
    private fun countDown() {
        var duration = 60
        mTickJob?.cancel()
        mTickJob = tickFlow {
            duration -= 1
            if (duration <= 0) {
                mTickJob?.cancel()
                // 结束
                binding.tvSendTitle.text = "发送验证码"
                binding.tvSendTitle.isEnabled = true
            } else {
                binding.tvSendTitle.text = "${duration}后重发"
                binding.tvSendTitle.isEnabled = false
            }
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkHasNewVersion() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(LoginIntent.FetchLastVersion)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.etPhone.removeTextChangedListener(textWatch)
        binding.etPassword.removeTextChangedListener(textWatch)
        binding.etSmsCode.removeTextChangedListener(textWatch)
        mTickJob?.cancel()
        mTickJob = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002 && resultCode == RESULT_OK && data != null && data.hasExtra("verifyMsg")) {
            val stringExtra = data.getStringExtra("verifyMsg") ?: ""
            val phone = binding.etPhone.text.toString().trim()
            lifecycleScope.launch {
                viewModel.intentChannel.send(LoginIntent.SendSmsCode(stringExtra, phone))
            }
        }
    }
}